export default class MqttClient {

  constructor(displayer, sceneId) {
    let signals = displayer.signals
    let baseTopic = '@forallcn/iotps/'+ sceneId

    let client
    const options = {
      connectTimeout: 40000,
      clientId: 'forallcn-iotps-displayer-' + sceneId,
      username: 'admin',
      password: 'public',
      clean: true
    }
    client = mqtt.connect('ws://zhouwr.iot:8083/mqtt', options)

    this.client = client

    client.on('connect', (e) => {
      console.log("连接成功！！！", options)
      client.subscribe('@forallcn/iotps/#', {qos: 0}, (error) => {
        if (!error) {
          console.log('订阅成功')
        } else {
          console.log('订阅失败')
        }
      })
    })

    // 接收消息处理
    client.on('message', (topic, message) => {
      console.log('收到来自', topic, '的消息',message.toString())
      const data = JSON.parse(message.toString())
      switch (topic) {
        case baseTopic + '/data/receive':
          signals.dataReceived.dispatch(data)
          break
        case baseTopic + '/device/online':
          signals.deviceOnline.dispatch(data)
          break
        case baseTopic + '/device/offline':
          signals.deviceOffline.dispatch(data)
          break
        /* 移动主题：'@forallcn/iotps/function' */
        case baseTopic + '/device/function':
          signals.deviceFunction.dispatch(data)
          break
        default:
          console.log(data)
          break
      }
    })
  }
}
